﻿using Microsoft.AspNetCore.WebUtilities;
using PlatformUW.Entities.Dtos;
using PlatformUW.Entities.RequestFeatures;
using PlatformUW.Web.Features;
using System.Text.Json;

namespace PlatformUW.Web.HttpRepository
{
    public class SensorHttpRepository : ISensorHttpRepository
    {
        private readonly HttpClient _httpClient;

        public SensorHttpRepository(HttpClient client)
        {
            _httpClient = client;
        }

        public async Task<PagingResponse<SensorDto>> GetSensors(SensorParameter sensorParameters)
        {
            var queryStringParam = new Dictionary<string, string>
            {
                ["PageNumber"] = sensorParameters.PageNumber.ToString(),
            };

            var response = await _httpClient.GetAsync(
                QueryHelpers.AddQueryString("api/sensor/all", queryStringParam));
            var content = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                throw new ApplicationException(content);
            }

            var pagingReponse = new PagingResponse<SensorDto>
            {
                Items = JsonSerializer.Deserialize<List<SensorDto>>(
                    content,
                    new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
            };

            return pagingReponse;
        }
    }
}
